import { message } from "antd";
import axios from "axios";
import type { AxiosError, AxiosRequestConfig } from "axios";

interface Ibase<T = string | null>{
    data:T,
    code:number,
    msg:string
}

export const BASE_URL = "http://localhost:3000";
const request = axios.create({baseURL : BASE_URL});

export function handleErrorType(error: Error){
    return error as AxiosError<Ibase>
}

request.interceptors.request.use((config)=>{
    const token = localStorage.getItem("token");
    if (token) {
        config.headers.Authorization = token
    }
    return config
})

request.interceptors.response.use(
    (response)=>{
        const data = response?.data as Ibase;
        if(data.code === 0 && data.msg != undefined) message.success(data.msg);
        return response
    },
    (error)=>{
        const { response } = handleErrorType(error) || {};
        message.warning(response?.data?.msg ?? "出现未知错误，请重试"); 
    }
)

export default async function makeRequest<T>(
    url:string,
    option?:AxiosRequestConfig
){
    return (
        await request({
            url,
            ...option
        })
    ).data as Ibase<T>
}